using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Core;

namespace Forum.Business
{
    public class RoleListControl : ForumUserControl
    {
        protected Repeater list;

        protected override void OnLoad(EventArgs e)
        {
            if (!ValidatePermission(PermissionType.RoleAdmin))
            {
                throw new Exception("Access denied.");
            }
            if (!Page.IsPostBack && !AjaxManager.IsCallBack)
            {
                BindData();
            }
            AjaxManager.Register(this, "AjaxMethod");
        }

        private void BindData()
        {
            if (list == null)
            {
                return;
            }
            list.DataSource = RemoveCoreRoles(RoleManager.GetAllRoles());
            list.DataBind();
        }

        private EntityList RemoveCoreRoles(EntityList allRoles)
        {
            EntityList filterRoles = new EntityList();
            foreach (Role role in allRoles)
            {
                if (role.IsRoleType((long)RoleType.AllowVisible))
                {
                    filterRoles.Add(role);
                }
            }
            return filterRoles;
        }

        #region Ajax Method

        [AjaxMethod]
        public int DeleteRole(int roleId)
        {
            Role role = RoleManager.GetRole(roleId);
            if (role == null)
            {
                return 0;
            }
            if (!role.IsRoleType((long)RoleType.AllowDelete))
            {
                return -1;
            }
            RoleManager.Delete(roleId);
            return 1;
        }

        [AjaxMethod]
        public int DeleteRoles(string roleIds)
        {
            if (string.IsNullOrEmpty(roleIds))
            {
                return 0;
            }
            string[] roleIdArray = roleIds.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
            int roleId = 0;
            foreach (string stringRoleId in roleIdArray)
            {
                try
                {
                    roleId = Int32.Parse(stringRoleId);
                }
                catch
                {
                    continue;
                }
                if (roleId > 0)
                {
                    int result = DeleteRole(roleId);
                    if (result != 1)
                    {
                        return result;
                    }
                }
            }
            return 1;
        }

        #endregion
    }
}